import { defineStore } from 'pinia'
import { store } from '@/store'
import { commonType } from './types'
import { darken, lighten, opciten } from '@/utils/colorHandle'

export const useCommonStore = defineStore({
  id: 'music-common',
  state: (): commonType => ({
    theme: localStorage.getItem('theme') ?? '#202023',
    account: JSON.parse(localStorage.getItem('account')) ?? {},
    profile: JSON.parse(localStorage.getItem('profile')) ?? {},
    cookie: localStorage.getItem('cookie') ?? ''
  }),
  actions: {
    setPropertyPrimary(mode: string, i: number, color: string) {
      document.documentElement.style.setProperty(
        `--el-color-primary-${mode}-${i}`,
        mode === 'dark' ? darken(color, i / 16) : lighten(color, i / 16)
      )
    },
    setTheme(targetTheme: string) {
      this.theme = targetTheme
      localStorage.setItem('theme', this.theme)
      if (targetTheme !== '#202023') {
        document.documentElement.classList.remove('dark')
        document.documentElement.style.setProperty(
          '--music-base-color',
          targetTheme
        )
        document.documentElement.style.setProperty(
          '--music-base-color-light',
          opciten(targetTheme, 0.06)
        )
        document.documentElement.style.setProperty(
          '--el-color-primary',
          targetTheme
        )
        for (let i = 1; i <= 2; i++) {
          this.setPropertyPrimary('dark', i, targetTheme)
        }
        for (let i = 1; i <= 9; i++) {
          this.setPropertyPrimary('light', i, targetTheme)
        }
      } else {
        document.documentElement.classList.add('dark')
        document.documentElement.style.setProperty(
          '--music-base-color',
          '#ec4141'
        )
        document.documentElement.style.setProperty(
          '--music-base-color-light',
          opciten('#ec4141', 0.07)
        )
        document.documentElement.style.setProperty(
          '--el-color-primary',
          '#ec4141'
        )
        for (let i = 1; i <= 2; i++) {
          this.setPropertyPrimary('dark', i, '#ec4141')
        }
        for (let i = 1; i <= 9; i++) {
          this.setPropertyPrimary('light', i, '#ec4141')
        }
      }
    }
  }
})

export function useCommonStoreHook() {
  return useCommonStore(store)
}
